import fs from 'node:fs';
import { AnyKey } from '@p/utils';
import { config } from '@e/config';
import { __path } from '@e/methods/path';
import { ipcMain, shell } from 'electron';
import { getWindowByEvent } from './global';
import { WindowObject } from '@p/main-windowObject';
import { batchCreateWindow } from '@e/createWindow';
import { selectDirDialog, selectFileDialog, selectMdFileDialog, errorDialog, savePathDialog } from '@e/dialog';

// 获取基本信息
ipcMain.handle('get-baseInfo', (event) => {
	const { filePath, id, state } = (getWindowByEvent(event) as WindowObject).service;

	return {
		id,
		filePath,
		state,
		name: config.getName(),
		version: config.getVersion(),
	};
});

// 获取文档信息
ipcMain.handle('get-document-info', async (event, _path) => {
	const { service } = getWindowByEvent(event);

	return await service.getDocumentInfo(_path);
});

// 选择文件
ipcMain.handle('select-file', (event, title, defaultPath, filters, multiple, showHiddenFiles) => {
	const { window } = getWindowByEvent(event);

	return selectFileDialog(window, title, defaultPath, filters, multiple, showHiddenFiles);
});

// 选择文件夹
ipcMain.handle('select-dir', (event, title, defaultPath, multiple, showHiddenFiles) => {
	const { window } = getWindowByEvent(event);

	return selectDirDialog(window, title, defaultPath, multiple, showHiddenFiles);
});

// 选择 Markdown 文件
ipcMain.handle('select-md-file', (event, title, defaultPath, multiple, showHiddenFiles) => {
	const { window } = getWindowByEvent(event);

	return selectMdFileDialog(window, title, defaultPath, multiple, showHiddenFiles);
});

// 选择保存路径
ipcMain.handle('select-save-path', (event, title, defaultPath, filter) => {
	const { window } = getWindowByEvent(event);

	return savePathDialog(window, title, defaultPath, filter);
});

// 创建窗口
ipcMain.on('create-window', (_event, paths) => {
	batchCreateWindow(paths);
});

// 检查路径
ipcMain.handle('check-path', (_event, _path, type: 'file' | 'dir' | 'exist') => {
	switch (type) {
		case 'file':
			return __path.check.file(_path);
		case 'dir':
			return __path.check.dir(_path);
		case 'exist':
			return __path.check.exist(_path);
	}
});

// 加载图片
ipcMain.handle('load-network-image', (event, url) => {
	const { service } = getWindowByEvent(event);

	return service.loadImageFromNetwork(url);
});

// 获取图片的目录信息
ipcMain.handle('get-image-dir-info', (event) => {
	const { service } = getWindowByEvent(event);

	return service.getImageDirInfo();
});

// 设置颜色方案
ipcMain.on('set-color-scheme', (event, mode) => {
	const { service } = getWindowByEvent(event);

	service.setColorScheme(mode);
});

// 使用默认浏览器打开网址
ipcMain.on('open-external', (_event, url) => {
	shell.openExternal(url);
});

// 关闭当前文档
ipcMain.on('close-current-document', (event) => {
	const { service } = getWindowByEvent(event);

	service.closeCurrentDocument();
});

// 查询替换信息
ipcMain.handle('query-images-reference-path-replace-info', (event, arr) => {
	const { service } = getWindowByEvent(event);

	return service.queryImageReferencePathReplaceInfo(arr);
});

// 展示路径
ipcMain.on('show-path', (_event, path) => {
	__path.show(path);
});

// 消息id + 1
ipcMain.handle('message-id-add', (event) => {
	const { service } = getWindowByEvent(event);

	return ++service.messageID;
});

// 获取 configFile 的值
ipcMain.handle('get-config-file', () => {
	return JSON.parse(JSON.stringify(config.configFile));
});

// 设置 configFile 的值
ipcMain.on('set-config-file', (_, value) => {
	if (config.checkConfigFileValue(value)) {
		const _value = value as AnyKey<any>;
		for (const key in _value) {
			(config.configFile as AnyKey<any>)[key] = _value[key];
		}
	}
});

// 恢复 configFile 默认的值
ipcMain.handle('restore-default--config-file', (event) => {
	const { service } = getWindowByEvent(event);

	const _value = config.configFileDefaultValue as AnyKey<any>;
	for (const key in _value) {
		(config.configFile as AnyKey<any>)[key] = _value[key];
	}

	service.sendMessage('insert', 'info', '已恢复默认设置');

	return _value;
});

// 获取图片引用关系
ipcMain.handle('get-image-citation-info', (event, paths) => {
	const { service } = getWindowByEvent(event);

	// return service.getImageCitationInfo(paths);
});

// 删除文件
ipcMain.handle('delete-file', (_event, paths: string | string[]) => {
	return new Promise((resolve, reject) => {
		const arr = Array.isArray(paths) ? paths : [paths];

		arr.forEach((file) => {
			try {
				fs.unlinkSync(file);
			} catch (error) {
				errorDialog('错误', (error as Error).message);
				reject(error);
			}
		});

		resolve(true);
	});
});

// 文件拖入窗口事件
ipcMain.on('drop-file', (_e, paths: string[]) => {
	const arr: string[] = [];
	paths.forEach((file) => {
		if (__path.check.isMdFilePath(file)) {
			arr.push(file);
		}
	});

	batchCreateWindow(arr);
});

// 判断是否为 markdown 文档路径
ipcMain.handle('is-md-file-path', (_e, filePath) => {
	return __path.check.isMdFilePath(filePath);
});

// 模式1
ipcMain.handle('mode1', (event, obj) => {
	const { service } = getWindowByEvent(event);

	service.mode1Fn(obj);
});

// 模式2
ipcMain.handle('mode2', (event, obj) => {
	const { service } = getWindowByEvent(event);

	service.mode2Fn(obj);
});

// 模式3
ipcMain.handle('mode3', (event, obj) => {
	const { service } = getWindowByEvent(event);

	service.mode3Fn(obj);
});

// 模式4
ipcMain.handle('mode4', (event, obj) => {
	const { service } = getWindowByEvent(event);

	service.mode4Fn(obj);
});

// 模式6
ipcMain.handle('mode6', (event, obj) => {
	const { service } = getWindowByEvent(event);

	service.mode6Fn(obj);
});
